<template>
  <div class="section-wrap addPlan" @click="openRightIndex=-1">
    <!-- 头部 -->
     <div class="headerBox">
    <div class="header">
      <x-icon type="ios-arrow-left" size="" class="icon-white" @click="goBack"></x-icon>
      新增量化考核计划
    </div>
    </div>
    <div class="form-section" style="margin-top: 40px;">
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>被考核单位<span class="must_span">*</span></label>
        </div>
        <div class="input_div" @click="getCompany(0)">
          <input type="text"
                 placeholder="请选择"
                 :disabled="isDisabled" v-model="params.beDepartName">
          <x-icon type="ios-arrow-right" size="22" class="icon-right" ></x-icon>
        </div>
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>被考核单位负责人</label>
        </div>
        <div class="input_div">
          <input type="text" v-model="params.charge"
          disabled>
        </div>
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>考核表名称</label>
        </div>
        <!-- <group>
            <datetime v-model="endTime"></datetime>
        </group> -->
        <div class="input_div" @click="flag=true">
          <input type="text"
                 placeholder="请选择"
                 v-model="params.classifyTwoName" disabled>
          <input type="hidden"
                 :disabled="isDisabled" v-model="params.classifyTwoId">
          <x-icon type="ios-arrow-right" size="22" class="icon-right"></x-icon>
        </div>
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>量化考核时间</label>
        </div>
        <group>
          <datetime placeholder="请选择" v-model="dataTime"></datetime>
        </group>
        <!--<div class="input_div">
            <input type="text"
                   placeholder="请选择"
                   :disabled="isDisabled">
            <x-icon type="ios-arrow-right" size="22" class="icon-right"></x-icon>
        </div>-->
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>考核组长</label>
        </div>
        <div class="input_div" @click="getCompany(1)">
          <input type="text"
                 v-model="params.checkGroupLeaderName"
                 placeholder="请选择" disabled
          >
          <x-icon type="ios-arrow-right" size="22" class="icon-right" ></x-icon>
        </div>
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>抄送接收人</label>
        </div>
        <div class="input_div" @click="classValue3=true">
          <input type="text"
                 v-model="params.receivrtName"
                 placeholder="请选择"
                 disabled
          >
          <x-icon type="ios-arrow-right" size="22" class="icon-right" ></x-icon>
        </div>
 <!--       <div class="input_div" @click="getCompany(2)">
          <input type="text"
                 placeholder="请选择"
                 v-model="params.receivrtName"
          >
          <x-icon type="ios-arrow-right" size="22" class="icon-right" ></x-icon>
        </div>-->
      </div>
      <div class="form-item form-item-style1">
        <div class="label-title">
          <label>考核编号</label>
        </div>
        <div class="input_div">
          <input type="text"
                 placeholder="年月日+流水号，自动生成"
                 disabled>
        </div>
      </div>
      <div class="info_div3">
        <p>考核分工<span>（{{lis.length}}组）</span></p>
        <span class="add_team" @click="add">新增</span>
      </div>
      <div class="member_div">
        <ul class="member_list">
          <li v-for="(list,index) in lis" v-bind:key="list.id" style="position: relative">
            <v-touch v-on:swipeleft="onSwipeLeft(index)" tag="div" class="v-touch">
            <div class="form-item form-item-style1">
              <div class="label-title">
                <label>成员：</label>
              </div>
              <div class="input_div"  @click="getCompany(3,index)">
                <input type="text" class="member1"
                       placeholder="请选择"
                       v-model="list.divisionProsonName"
                       :disabled="isDisabled">
                <x-icon type="ios-arrow-right" size="22" class="icon-right"
                       ></x-icon>
              </div>
            </div>
            <div class="form-item form-item-style1" style="border-bottom: none;">
              <div class="label-title">
                <label>分工（考核项）：</label>
              </div>
              <div class="input_div" @click="getDivision(index)">
                <input type="text"
                       placeholder="请选择"
                       v-model="list.standardNameList"
                       :disabled="isDisabled">
                <x-icon type="ios-arrow-right" size="22" class="icon-right"
                        ></x-icon>
              </div>
            </div>
              <div style="height: 116px;width: 100px;position: absolute;top:0;right: 0;cursor: pointer" v-if="openRightIndex==index">
                <p style="width:50px;text-align:center;height: 116px;line-height:116px;background-color: red;color: #fff;float: left" @click="del(index)">删除</p>
                <p style="width:50px;text-align:center;height: 116px;line-height:116px;background-color: #ccc;color: #fff;float: right" @click="openRightIndex=-1">取消</p>
              </div>
            </v-touch>
          </li>

        </ul>
      </div>
      <div class="btns_div">
        <a class="submitBtn" @click="save(0)">保 存</a>
        <a class="cancelBtn" @click="save(1)">提 交</a>
      </div>
    </div>
    <div class="addPlan_select" @click="flag=!flag" v-if="flag">
      <ul class="planSel_list">
        <!--
                <li v-for="name in tableNamelist" @click="params.classifyTwoName=name.quantizeName,params.classifyTwoId=name.id">{{name.quantizeName}}</li>
        -->
        <li v-for="(name,index) in tableNamelist" :key="index" @click="changeValue(name.quantizeName,name.id)">
          {{name.quantizeName}}
        </li>
      </ul>
    </div>
    <div v-transfer-dom>
      <popup v-model="classValue" width="100%">
        <ztree
          :data="data"
          @nodeClick="nodeClick"
          :name="'departName'"
        ></ztree>
      </popup>
      <popup v-model="classValue1" width="100%">
        <select-depart v-if="$store.state.departId" :deptId="$store.state.departId" @selectUser='selectUser'></select-depart>
      </popup>
      <popup v-model="classValue2" width="100%">
        <div style="background: white">
          <el-tree
            :data="dataList"
            show-checkbox
            node-key="id"
            :default-checked-keys='checkedList'
            ref="tree"
            :props="def"
          >
          </el-tree>
          <div style="text-align:  center;margin-top: 10px;padding-bottom: 5px">
            <el-button size="mini" @click="classValue2=false">取消</el-button>
            <el-button size="mini" @click="getCheckedNodes">确认</el-button>
          </div>
        </div>
      </popup>
      <popup v-model="classValue3" width="100%" height="60%" style="padding-bottom:40px;">
        <div style="background: white;height:100%;overflow-y:scroll;padding-bottom:20px;">
          <el-tree
            v-if="classValue3"
            :data="data"
            node-key="id"
            :render-content="renderContent"
            :expand-on-click-node="true"
            ref="tree1"
            :props="defs"
          ></el-tree>
          <div style="text-align:  center;margin-top: 10px;padding-bottom: 5px;position: absolute;width: 100%;bottom: 15px;background-color: #eee;z-index: 10;">
            <el-button size="mini" @click="classValue3=false">取消</el-button>
            <el-button size="mini"  @click="addUser">确认</el-button>
          </div>
        </div>
      </popup>
    </div>
  </div>
</template>
<script>
  import ztree from "@commonComponents/tree"
  import selectDepart from "@commonComponents/selectUser/selectUser";
  import formatDate from "../../utils/formatDate";
  import {XHeader, Tabbar, TabbarItem, Group, Cell, TransferDom, Popup} from 'vux';

  export default {
    data() {
      return {
        classValue2: false,
        classValue3:false,
        itemId:'',
        checkedList: [],
        peosonlist:[],
        childData:{},
        lis: [{}],
        index: '',
        dataList: [],
        dataTime:'',
        ids:[],
        allQuestionLength: 0, // 所有问题项的数量总和
        openRightIndex:-1,
        def: {
          children: 'children',
          label: "quantizeName"
        },
        defs: {
          children: 'children',
          label: "departName"
        },
        isDisabled: true, // 是否禁止输入
        classValue: false,
        classValue1: false,
        selectDepartType: 0,
        tableNamelist: this.$store.state.tableTypeName.children,
        flag: false,
        checkData1:[],
        listIndex:'',
        params: {
          beDepartId: "",
          beDepartName: "",
          checkDepartName: "",
          checkDepartId: "",
          charge: "",
          status: 0,
          checkGroupLeaderId: "",
          checkGroupLeaderName: "",
          classifyTwoName: "",
          checkDate: "",
          receiverId: "",
          receivrtName: "",
          classifyOneId: this.$store.state.tableTypeName.id,
          classifyOneName: this.$store.state.tableTypeName.quantizeName,
          divisionList: [],
        },
        data: [
        ],
        userList: [{
          userName: "",
          userAccount: "",
          roleId: null,
          roleName: null,
          userOrder: "",
          stopUse: "",
          identifyId: "",
          departId: "",
          departName: "",
          departType: "",
          phone: "",
          userType: "",
          userTypeName: "",
          roleList: "",
          id: ""
        }]
      }
    },
    components: {
      ztree, Popup, selectDepart
    },
    directives: {
      TransferDom
    },
    created() {
    //  this.getUserList()
      this.queryInfo()
      this.examinedUnits()
    },

    methods: {
      tickMenuIdFilter: function(index) {
        var list=this.getChecked(index)
        console.log("list"+list)
        var resultArr = new Array();
        var getTickMenuId = function(obj) {
          if (undefined == obj || null == obj || !obj instanceof Object) {
            return;
          }
          if (list.indexOf(obj.id)>-1) {
             console.log('obj',obj)
            obj.disabled = true;
            resultArr.push(obj.id);
          }
          if (null != obj.children && obj.children instanceof Array) {
            for (let child of obj.children) {
              getTickMenuId(child);
            }
          }
        };

        return {
          filter: function(arr) {
            if (!arr instanceof Array) {
              return false;
            }
            resultArr = new Array();
            for (let rootMenu of arr) {
              getTickMenuId(rootMenu);
            }
            return resultArr;
          }
        };
      },
      goBack() {
        this.$router.go(-1)
      },

      del(index){
        this.openRightIndex=-1
        this.lis.splice(index,1)
      },
      add() {//增加按钮
        let cope = {}
        // 分工项已经被分工完
        let fgNum = 0
        if (this.lis.length > 0) {
          this.lis.forEach(item => {
            if (item.checkedList) {
              fgNum += item.checkedList.length
            }
          })
        }
        // 考核分工是否已经全部填完
        let isAllInput = false
        isAllInput = this.lis.every(item => {
          return item.divisionProsonId && item.standardIdList
        })
        if (!isAllInput) {
          this.$vux.toast.text('请先完成成员分工(考核项)')
          return false
        }
        if (fgNum >= this.allQuestionLength) {
          this.$vux.toast.text('分工(考核项)全部分工完成')
          return false
        }
        this.lis.push(cope);
      },
      getAllQuesCount (arr) {
        if (arr.length > 0) {
          this.allQuestionLength += arr.length
          arr.forEach(item => {
            this.getAllQuesCount(item.children)
          })
        }
      },
      changeValue(name, id) {
        this.params.classifyTwoName = name
        this.params.classifyTwoId = id
        this.lis = [{}]
        //  this.params.classifyTwoName=name.quantizeName,params.classifyTwoId=name.id
      },
      onSwipeLeft(index){
        this.openRightIndex=index
      },
      save(num) {//保存
        // 确认考核分工人都已全部填写完毕
        let isAllChekck = false
        isAllChekck = this.lis.some(item => {
          return !item.standardNameList || !item.divisionProsonName
        })
        if (isAllChekck) {
          this.$vux.toast.text("还有考核分工待完成")
          return;
        }
        if (this.params.beDepartName == null || this.params.beDepartName == '') {
          this.$vux.toast.text("请选择被考核单位")
          return;
        }
        if (this.params.classifyTwoName == null || this.params.classifyTwoName == '') {
          this.$vux.toast.text("请选择考核表")
          return;
        }
        if (this.params.checkGroupLeaderName == null || this.params.checkGroupLeaderName == '') {
          this.$vux.toast.text("请选择考核组长")
          return;
        }
        console.log(this.params.divisionList)
        this.params.divisionList = this.lis
        if (this.params.divisionList == null || this.params.divisionList.length==0) {
          this.$vux.toast.text("请选择考核分工")
          return;
        }
        if(this.params.divisionList.length>0){
          var a=this.params.divisionList.some(function(x) {
            return JSON.stringify(x) !='{}' && (x.checkedList!=null|| x.checkedList!=undefined);
          });
          console.log(a)
          if(!a){
            this.$vux.toast.text("请选择考核分工")
            return;
          }
        }
        if (this.dataTime) {
          this.params.checkDate=this.dataTime+" 00:00:00"
        }
        if (num == 0) {
          this.params.status = 0
        } else {
          this.params.status = 1
        }
        console.log(JSON.stringify(this.params))
        if (this.params.id == null || this.params.id == '') {
          this.$axiosAjax.save(this.params).then((res) => {
            if (res.data.success == true) {
              this.$vux.toast.text("操作成功")
              // this.$router.push("./quanPlan")
              this.$router.go(-1)
            }
          }).catch(
            (err) => {

            }
          )
        } else {
          this.$axiosAjax.assessmentUpdate(this.params).then((res) => {
            if (res.data.success == true) {
              this.$vux.toast.text("操作成功")
              // this.$router.push("./quanPlan")
              this.$router.go(-1)
            }
          }).catch(
            (err) => {

            }
          )
        }

      },
      getCheckedNodes() {//
        this.checkedList = this.$refs.tree.getCheckedNodes()
        let i = [];
        this.checkedList.forEach(item => {
          i.push(item.id);
        })
        this.lis[this.index].standardNameList = this.checkedList.map(x => x.quantizeName).join(',');
        this.lis[this.index].standardIdList = this.checkedList.map(x => x.id).join(',');
        this.checkedList = i
        this.lis[this.index].checkedList = i
        this.classValue2 = false
      },
      selectedDepart(data) {
        this.classValue1 = false;
      },
      getCompany(num, index) {
        this.openRightIndex=-1
        this.index = index
        if (num == 0) {
          this.classValue = true;
        //  this.examinedUnits()
        } else {
          this.classValue1 = true;
        }
        this.selectDepartType = num;
      },
      getDivision(index) {
        this.openRightIndex=-1
        if (this.lis[index].checkedList != null && this.lis[index].checkedList.length > 0) {
          this.checkedList = this.lis[index].checkedList
        } else {
          this.checkedList = []
        }
        this.index = index
        this.classValue2 = true;
        this.$axiosAjax.getDivision({classifyId: this.params.classifyTwoId}).then((res) => {
          if (res.data.success == true) {
            this.dataList = res.data.result
            this.getAllQuesCount(this.dataList)
            this.tickMenuIdFilter(index).filter(this.dataList);
            console.log(this.dataList)
          }
        }).catch(
          (err) => {

          }
        )
      },
      getChecked(index){
        var list=[]
        if(this.lis.length>0){
          this.lis.forEach((item,i)=>{
            console.log(item.checkedList)
            if(item.checkedList!=undefined&&item.checkedList.length>0&&i!=index){
              list=list.concat(item.checkedList)
            }

          })
        }
        return list;
      },
      examinedUnits() {
        this.$axiosAjax.examinedUnits({parentId: this.$store.state.departId || -1}).then((res) => {
          if (res.data.success == true) {
            this.data = res.data.result
            console.log(this.data)
          }
        }).catch(
          (err) => {

          }
        )
      },
      nodeClick(item) {
        if (item.departType == 6 || item.departType == 7 || item.departType == 8) {
          this.params.beDepartName = item.departName
          this.params.beDepartId = item.id
          this.params.charge = item.charge
          this.classValue = false
        } else {
          this.$vux.toast.text("只能选择项目部")
        }
      },
     /* getUserList() {
        this.$axiosAjax.getUserList({}).then((res) => {
          if (res.data.success == true) {
            this.data = res.data.result.items
          }
        }).catch(
          (err) => {

          }
        )
      },*/
      selectUser(data) {
        console.log(data);
        if (this.selectDepartType == 1) {
          this.params.checkGroupLeaderName = data.userName
          this.params.checkGroupLeaderId = data.id
        } else if (this.selectDepartType == 2) {
          this.params.receiverId = data.id
          this.params.receivrtName = data.userName
        } else {
          // 判断分工人是否重复选择
          let isRepeat = false
          isRepeat = this.lis.some(item => {
            return item.divisionProsonId == data.id
          })
          if (isRepeat) {
            this.$vux.toast.text('分工成员重复')
          } else {
            this.lis[this.index].divisionProsonId = data.id
            this.lis[this.index].divisionProsonName = data.userName
          }
        }
        this.classValue1 = false
      },
      queryInfo() {//查询详情
        let id = this.$route.query.id;
        if (id != null && id != '') {
          this.$axiosAjax.getPalnInfo({planId: id})
            .then(res => {
              if (res.data.success == true) {
                this.params = res.data.result;
                if (this.params.divisionList != null && this.params.divisionList.length > 0) {
                  this.lis = []
                  this.params.divisionList.forEach((item, i) => {
                    this.lis.push(item)
                    let types = item.standardIdList.split(',')
                    this.lis[i].checkedList = types
                    if(res.data.result.checkDate){
                      this.dataTime=res.data.result.checkDate.substring(0,10)
                    }
                    console.log(this.lis)
                    console.log(item)
                  })
                }
              }
            })
            .catch(err => {
            });
        }
      },
      append (data) {
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        var a =this.peosonlist
        if(a.length>0){
          a.forEach((item,i)=>{
            data.children.unshift({ id: item.id, departName: item.userName,type:"0", children: [] })
          })
        }
      },
      renderContent (h, { node, data, store }) {
        if(data.type=='0'){
          return (
            <span class="span">
            <span>
            <span class="ll" on-click={ () => this.nodeClicks(data) }>
            <el-checkbox on-change={ () => this.test(data) }>{node.label}</el-checkbox></span>
        </span>
          </span>
        )

        }else{
          return (
            <span class="span">
            <span>
            <span on-click={ () => this.nodeClicks(data) }>{node.label}
        </span>
          </span>
          </span>
        )
        }
      },
      test(data){
        if(this.ids.indexOf(data)==-1){
          this.ids.push(data)
        }else{
          this.ids.splice(data,1)
        }
      },
      addUser(){
        this.classValue3=false
        if(this.ids.length>0){
          this.params.receiverId = this.ids.map(x => x.id).join(',');
          this.params.receivrtName = this.ids.map(x => x.departName).join(',');
        }
      },
      nodeClicks(item) {
        if(this.itemId==item.id){
          return;
        }
        if(item.type=='0'){
          return;
        }
        this.itemId=item.id
        this.$axiosAjax.getUserList({departId:item.id}).then((res) => {
          if(res.data.success==true){
            if(res.data.result.totalCount>0){
              console.log(res.data.result)
              this.peosonlist = res.data.result.items;
              this.append (item)
            }
          }
        }).catch(
          (err)=>{

          }
        )
      },
    },
  }
</script>
<style lang="less" scoped>
  .span{
    flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;
  }
  .must_span {
    color: #ff0000;
  }

  .form-item {
    .input_div {
      .vux-x-icon {
        fill: #999;
        float: right;
        margin-top: 17px;
      }
    }
  }

  .info_div3 {
    height: 55px;
    line-height: 45px;
    padding: 0 20px;
    border-top: 10px solid #ebeef2;
    p {
      float: left;
      color: #469b7a;
      font-size: 16px;
      font-weight: bold;
    }
    .add_team {
      float: right;
      display: block;
      font-size: 12px;
      background: url("/static/images/add_new_icon.png") no-repeat right center;
      background-size: 16px 16px;
      padding-right: 20px;
      color: #999;
    }
  }

  .member_div {
    .member_list {
      li {
        border-top: 5px solid #ebeef2;
      }
      .member1 {
        color: #ff0000;
      }
      .member2 {
        color: #15bd84;
      }
    }
  }

  .btns_div {
    background: #ebeef2;
    padding: 30px 20px 55px;
    justify-content: space-between;
    display: flex;
    a {
      height: 40px;
      border-radius: 20px;
      display: inline-block;
      width: 140px;
      text-align: center;
      line-height: 40px;
      color: #fff;
    }
    .submitBtn {
      background: #469b7a;
    }
    .cancelBtn {
      background: #ffb400;
    }
  }

  .addPlan_select {
    position: fixed;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .5);
    top: 0;
    left: 0;
    z-index: 10;
    .planSel_list {
      width: 60%;
      margin: 0 auto;
      padding-top: 150px;
      li {
        border-radius: 10px;
        height: 57px;
        line-height: 57px;
        text-align: center;
        background: #fff;
        margin-bottom: 6px;
        color: #469b7a;
        font-size: 16px;
      }
    }
  }
  .v-touch {
    touch-action: pan-y !important;
  }
</style>
<style>
  .addPlan .vux-cell-placeholder{
    font-size: 14px;
    margin-right: 10px!important;
  }
  .addPlan .input_div input{
    width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
